import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Typography,
  Descriptions,
  Button,
  Modal,
  Form,
  Input,
  message,
  Statistic,
  Tag,
  Space,
  Divider,
  Popconfirm,
  Tabs,
  Alert,
  Upload,
  Image,
} from 'antd';
import {
  UserOutlined,
  EditOutlined,
  LockOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  GiftOutlined,
  KeyOutlined,
  TrophyOutlined,
  CalendarOutlined,
  CameraOutlined,
} from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import { getCurrentUser, updateUserProfile, changePassword, getUserStats, regeneratePasskey, uploadAvatar } from '../api/user';
import { User, USER_CLASS_MAP } from '../types';
import { formatBytes, formatDateTime, formatShareRatio } from '../utils/format';

const { Title, Text, Paragraph } = Typography;

interface UserStats {
  torrentCount: number;
  seedingCount: number;
  leechingCount: number;
  inviteCount: number;
  topicCount: number;
  todayUpload: number;
  todayDownload: number;
  weekUpload: number;
  weekDownload: number;
  monthUpload: number;
  monthDownload: number;
}

const Profile: React.FC = () => {
  const { user: authUser } = useAuth();
  const [user, setUser] = useState<User | null>(null);
  const [userStats, setUserStats] = useState<UserStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [editForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  useEffect(() => {
    fetchUserProfile();
    fetchUserStats();
  }, []);

  const fetchUserProfile = async () => {
    try {
      setLoading(true);
      const response = await getCurrentUser();
      if (response.code === 200) {
        setUser(response.data);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      message.error('获取用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchUserStats = async () => {
    console.log('=== 开始获取用户统计信息 ===');
    try {
      const response = await getUserStats();
      console.log('User stats response:', response);
      if (response.code === 200) {
        console.log('User stats data:', response.data);
        setUserStats(response.data);
      }
    } catch (error) {
      console.error('获取用户统计失败:', error);
    }
  };

  const handleUpdateProfile = async (values: any) => {
    try {
      const response = await updateUserProfile(values);
      if (response.code === 200) {
        setUser(response.data);
        setEditModalVisible(false);
        message.success('个人信息更新成功');
        editForm.resetFields();
      } else {
        message.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新个人信息失败:', error);
      message.error('更新失败，请稍后重试');
    }
  };

  const handleChangePassword = async (values: any) => {
    try {
      const response = await changePassword(values);
      if (response.code === 200) {
        setPasswordModalVisible(false);
        message.success('密码修改成功');
        passwordForm.resetFields();
      } else {
        message.error(response.message || '修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      message.error('修改失败，请稍后重试');
    }
  };

  const handleRegeneratePasskey = async () => {
    try {
      const response = await regeneratePasskey();
      if (response.code === 200) {
        message.success('Passkey重新生成成功');
        fetchUserProfile(); // 重新获取用户信息
      } else {
        message.error(response.message || '重新生成失败');
      }
    } catch (error) {
      console.error('重新生成Passkey失败:', error);
      message.error('重新生成失败，请稍后重试');
    }
  };

  const openEditModal = () => {
    editForm.setFieldsValue({
      email: user?.email,
      nickname: user?.username,
    });
    setEditModalVisible(true);
  };

  const handleAvatarUpload = async (file: any) => {
    try {
      const response = await uploadAvatar(file);
      if (response.code === 200) {
        // 重新获取用户信息以包含新的头像URL
        fetchUserProfile();
        message.success('头像上传成功');
      } else {
        message.error(response.message || '头像上传失败');
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      message.error('上传头像失败，请稍后重试');
    }
  };

  if (!user) {
    return (
      <Card loading={loading}>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text>加载中...</Text>
        </div>
      </Card>
    );
  }

  const userClassInfo = USER_CLASS_MAP[user.userClass as keyof typeof USER_CLASS_MAP];

  return (
    <div>
      <Row gutter={16}>
        {/* 用户基本信息 */}
        <Col span={24}>
          <Card>
            <Row gutter={16} align="middle">
              <Col>
                <div style={{ position: 'relative', display: 'inline-block' }}>
                  {user.avatar ? (
                    <Image
                      src={`http://localhost:8080${user.avatar}`}
                      alt="用户头像"
                      width={80}
                      height={80}
                      style={{ borderRadius: '50%', objectFit: 'cover' }}
                      fallback="" />
                  ) : (
                    <Avatar size={80} icon={<UserOutlined />} />
                  )}
                  <Upload
                    accept="image/*"
                    showUploadList={false}
                    beforeUpload={handleAvatarUpload}
                    customRequest={() => {}} // 阻止默认上传行为
                  >
                    <Button
                      type="primary"
                      shape="circle"
                      icon={<CameraOutlined />}
                      size="small"
                      style={{
                        position: 'absolute',
                        bottom: 0,
                        right: 0,
                        zIndex: 1
                      }}
                    />
                  </Upload>
                </div>
              </Col>
              <Col flex="auto">
                <Space direction="vertical" size="small">
                  <Title level={2} style={{ margin: 0 }}>
                    {user.username}
                  </Title>
                  <Space>
                    <Tag color={userClassInfo?.color || 'default'}>
                      <TrophyOutlined /> {userClassInfo?.text || '未知等级'}
                    </Tag>
                    <Text type="secondary">
                      <CalendarOutlined /> 注册时间: {formatDateTime(user.createdTime)}
                    </Text>
                  </Space>
                  <Text type="secondary">
                    上次登录: {user.lastLoginTime ? formatDateTime(user.lastLoginTime) : '从未登录'}
                  </Text>
                </Space>
              </Col>
              <Col>
                <Space>
                  <Button icon={<EditOutlined />} onClick={openEditModal}>
                    编辑资料
                  </Button>
                  <Button icon={<LockOutlined />} onClick={() => setPasswordModalVisible(true)}>
                    修改密码
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        {/* 统计信息 */}
        <Col span={24}>
          <Card title="统计信息">
            <Row gutter={16}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="上传量"
                    value={formatBytes(user.uploaded)}
                    prefix={<CloudUploadOutlined style={{ color: '#52c41a' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="下载量"
                    value={formatBytes(user.downloaded)}
                    prefix={<CloudDownloadOutlined style={{ color: '#1890ff' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="分享率"
                    value={user.shareRatio ? user.shareRatio.toFixed(2) : '0.00'}
                    prefix={<TrophyOutlined style={{ color: '#fa8c16' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="魔力值"
                    value={user.bonusPoints}
                    prefix={<GiftOutlined style={{ color: '#eb2f96' }} />}
                  />
                </Card>
              </Col>
            </Row>

            {userStats && (
              <>
                <Divider />
                <Tabs 
                  defaultActiveKey="today"
                  items={[
                    {
                      key: 'today',
                      label: '今日统计',
                      children: (
                        <Row gutter={16}>
                          <Col span={12}>
                            <Statistic
                              title="今日上传"
                              value={formatBytes(userStats.todayUpload)}
                              prefix={<CloudUploadOutlined />}
                            />
                          </Col>
                          <Col span={12}>
                            <Statistic
                              title="今日下载"
                              value={formatBytes(userStats.todayDownload)}
                              prefix={<CloudDownloadOutlined />}
                            />
                          </Col>
                        </Row>
                      )
                    },
                    {
                      key: 'week',
                      label: '本周统计',
                      children: (
                        <Row gutter={16}>
                          <Col span={12}>
                            <Statistic
                              title="本周上传"
                              value={formatBytes(userStats.weekUpload)}
                              prefix={<CloudUploadOutlined />}
                            />
                          </Col>
                          <Col span={12}>
                            <Statistic
                              title="本周下载"
                              value={formatBytes(userStats.weekDownload)}
                              prefix={<CloudDownloadOutlined />}
                            />
                          </Col>
                        </Row>
                      )
                    },
                    {
                      key: 'month',
                      label: '本月统计',
                      children: (
                        <Row gutter={16}>
                          <Col span={12}>
                            <Statistic
                              title="本月上传"
                              value={formatBytes(userStats.monthUpload)}
                              prefix={<CloudUploadOutlined />}
                            />
                          </Col>
                          <Col span={12}>
                            <Statistic
                              title="本月下载"
                              value={formatBytes(userStats.monthDownload)}
                              prefix={<CloudDownloadOutlined />}
                            />
                          </Col>
                        </Row>
                      )
                    }
                  ]}
                />
              </>
            )}
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        {/* 详细信息 */}
        <Col span={24}>
          <Card title="详细信息">
            <Descriptions column={2} bordered>
              <Descriptions.Item label="用户ID">{user.id}</Descriptions.Item>
              <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{user.email}</Descriptions.Item>
              <Descriptions.Item label="等级">
                <Tag color={userClassInfo?.color}>{userClassInfo?.text}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {formatDateTime(user.createdTime)}
              </Descriptions.Item>
              <Descriptions.Item label="上次登录">
                {user.lastLoginTime ? formatDateTime(user.lastLoginTime) : '从未登录'}
              </Descriptions.Item>
              {userStats && (
                <>
                  <Descriptions.Item label="发布种子">{userStats.torrentCount}</Descriptions.Item>
                  <Descriptions.Item label="发布帖子">{userStats.topicCount}</Descriptions.Item>
                  <Descriptions.Item label="做种中">{userStats.seedingCount}</Descriptions.Item>
                  <Descriptions.Item label="下载中">{userStats.leechingCount}</Descriptions.Item>
                  <Descriptions.Item label="可用邀请">{userStats.inviteCount}</Descriptions.Item>
                </>
              )}
            </Descriptions>

            <Divider />
            
            <Alert
              message="Passkey"
              description={
                <div>
                  <Paragraph copyable={{ text: user.passkey }}>
                    <Text code>{user.passkey}</Text>
                  </Paragraph>
                  <Text type="secondary">
                    Passkey用于客户端连接，请妥善保管，不要泄露给他人。
                  </Text>
                  <div style={{ marginTop: 8 }}>
                    <Popconfirm
                      title="确定要重新生成Passkey吗？"
                      description="重新生成后，所有正在使用的客户端都需要更新Passkey。"
                      onConfirm={handleRegeneratePasskey}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button icon={<KeyOutlined />} type="link" danger>
                        重新生成Passkey
                      </Button>
                    </Popconfirm>
                  </div>
                </div>
              }
              type="info"
              showIcon
            />
          </Card>
        </Col>
      </Row>

      {/* 编辑资料模态框 */}
      <Modal
        title="编辑个人资料"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
      >
        <Form form={editForm} onFinish={handleUpdateProfile} layout="vertical">
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[
              { required: true, message: '请输入昵称' },
              { min: 2, message: '昵称至少2个字符' },
              { max: 20, message: '昵称不能超过20个字符' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="个人简介" name="bio">
            <Input.TextArea rows={4} placeholder="介绍一下自己..." />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
      >
        <Form form={passwordForm} onFinish={handleChangePassword} layout="vertical">
          <Form.Item
            label="当前密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                修改密码
              </Button>
              <Button onClick={() => setPasswordModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile; 